package info.macnana.online.jwt.authentication;

import com.alibaba.fastjson.JSON;
import info.macnana.online.core.base.ResponseResult;
import info.macnana.online.core.constant.Code;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * author: zhengheng
 * github: https://github.com/macnana777
 * email: 517862340@qq.com
 * <p>
 * Date: 2017-08-08 16:09
 * Description: 当访问的资源没有权限，会调用这里
 * Copyright(©) 2017 by zhengheng.
 */
public class NoAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.setStatus(HttpServletResponse.SC_OK);
        ResponseResult result = ResponseResult.error(Code.INVALID_TOKEN);
        response.getWriter().println(JSON.toJSONString(result));
        response.getWriter().flush();
    }

}
